package com.yuantong.xyerp.rest.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.yuantong.xyerp.core.api.dto.UserDto;
import com.yuantong.xyerp.core.api.enums.EnumMsgCode;
import com.yuantong.xyerp.core.api.exception.YuantongException;
import com.yuantong.xyerp.core.api.model.base.RestResponseModel;
import com.yuantong.xyerp.core.api.service.IOrganizationService;
import com.yuantong.xyerp.core.api.service.IRoleService;
import com.yuantong.xyerp.core.api.service.IUserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * Created by Jianguo.Yin on 2021-07-15.
 */
@Slf4j
@Api(tags = "员工接口")
@RestController
@RequestMapping("/user")
public class UserExportController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IOrganizationService organizationService;





    // 关于自定义导出数据, 前端传dto
    @ApiOperation(value = "导出员工数据",httpMethod = "POST", produces = "application/octet-stream")
    @PostMapping(value = "/export", produces = "application/octet-stream;charset=utf-8")
    public void exportEmployee(HttpServletResponse response,
                               @ApiParam(value = "条件选择中的角色id") @RequestParam(value = "roleId",required = false) String roleId,
                               @ApiParam(value = "条件选择中的部门id") @RequestParam(value = "organizationId",required = false) String organizationId,
                               @ApiParam(value = "条件选择中的用户输入的查询参数") @RequestParam(value = "fuzzy",required = false) String fuzzy,
                               @ApiParam("用户勾选的员工") @RequestBody(required = false) List<UserDto> userDtos) {
        // List<UserDto> list = userService.findByFuzzy(roleId, null,null,null);
        List<UserDto> list = userService.findByFuzzy(roleId, organizationId, fuzzy, userDtos);
        // List<UserDto> list = userService.findByFuzzy(roleId, null, null, userDtos);
        // List<UserDto> list = userService.findByFuzzy(null, null, null, null);
        ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, UserDto.class, list);
        ServletOutputStream outputStream = null;
        try {
            /**用 流的形式 */
            response.setContentType("application/octet-stream");
            //中文乱码
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //TODO: 员工.xls 要插入到 t_user 中, 但是 t_user 中有登录数据/敏感数据(password),
    // 明显, 员工.xls是不可能存放 password 的, 但是 t_user 中的 passowrd 是验证登录用的,
    // 总之, 员工.xls 插入到 t_user 后会造成 password 字段缺失, 插入了也没法登录...
    // 解决方法一: 将 t_user表字段 password 默认值设为"12345678", 这样新增员工的密码就是12345678

    @ApiOperation(value = "导入员工数据")
    @ApiImplicitParams({@ApiImplicitParam(name="file",value = "上传文件",dataType = "MultipartFile")})
    @PostMapping(value = "/import")
    public RestResponseModel importEmployee(MultipartFile file){
        ImportParams params = new ImportParams();
        //去掉标题行
        params.setTitleRows(1);

        try {

            List<UserDto> list = ExcelImportUtil.importExcel(file.getInputStream(), UserDto.class, params);

            for (int i = list.size()-1; i >=0; i--) {
                UserDto user = list.get(i);
                // 解决导出的表的问题: Excel 的 cell 的大小和默认导出的cell大小相同时, 会导致 poi 认为Excel 在这一行是数据的,
                // 解决方案: 可用 if 去除list中的这条空数据, 判断关键信息是否为 null,  null 就去除这条数据
                if (user.getLoginName() != null){
                    // 手动增加 uuid
                    user.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    // 设置默认密码
                    user.setPassword("12345678");
                    // 解决关联关系, 如excel中是 部门名称, 要转为 RoleId 存入 UserDto
                    user.setRoleId(roleService.findRoleByUser(user).getId());
                    user.setOrganizationId(organizationService.findOrganizationByName(user).getId());
                    continue;
                }
                list.remove(i);
            }
            if (userService.saveBatchByUserDtos(list) != 0){
                return RestResponseModel.SUCCESS(EnumMsgCode.MSG_SUCCESS);
            }
            throw new YuantongException(EnumMsgCode.UPLOAD_ERROR);

        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new YuantongException(EnumMsgCode.UPLOAD_ERROR);
    }
}
